package cn.mengfly.testnrz.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.UnpooledByteBufAllocator;

import java.nio.charset.StandardCharsets;

public class WriteReadTest {

    public static void main(String[] args) {
        ByteBuf pooledHeapBuf = PooledByteBufAllocator.DEFAULT.heapBuffer();
        ByteBuf pooledHeadBuf2 = PooledByteBufAllocator.DEFAULT.buffer();
        ByteBuf pooledDirectBuf = PooledByteBufAllocator.DEFAULT.directBuffer();

        ByteBuf unPooledHeapBuf = UnpooledByteBufAllocator.DEFAULT.buffer();
        ByteBuf unPooledHeadBuf2 = UnpooledByteBufAllocator.DEFAULT.directBuffer();
        ByteBuf unPooledDirectBuf = UnpooledByteBufAllocator.DEFAULT.heapBuffer();

        testHeapBuffer();

        testDirectBuffer();
    }

    private static void testDirectBuffer() {
        ByteBuf directBuffer = ByteBufAllocator.DEFAULT.directBuffer();
        directBuffer.writeBytes("测试直接内存buffer".getBytes(StandardCharsets.UTF_8));
        if (!directBuffer.hasArray()) {
            int length = directBuffer.readableBytes();
            byte[] array = new byte[length];
            directBuffer.getBytes(directBuffer.readerIndex(), array);
            System.out.println(new String(array, StandardCharsets.UTF_8));
        }
        directBuffer.release();
    }

    private static void testHeapBuffer() {
        ByteBuf heapBuffer = ByteBufAllocator.DEFAULT.heapBuffer();
        heapBuffer.writeBytes("测试堆内存数据".getBytes(StandardCharsets.UTF_8));
        if(heapBuffer.hasArray()) {
            byte[] array = heapBuffer.array();
            int offset = heapBuffer.arrayOffset() + heapBuffer.readerIndex();
            int length = heapBuffer.readableBytes();
            System.out.println(new String(array, offset, length, StandardCharsets.UTF_8));
        }
        heapBuffer.release();
    }
}
